import Vue from "vue";
import App from "./App.vue";
import router from "./router";
//全局前置守卫
router.beforeEach((to, from, next) => {
  //檢查token的存放數組
  const examineToken = ["/person","/personExit","/personCollect","/personAttention"];
  if (examineToken.indexOf(to.path) > -1) {
    if (!localStorage.getItem("token")) {
     return router.push("/login");
    }
  }
  next();
});
//vant插件
import Vant from "vant";
import "vant/lib/index.css";
import { Toast } from "vant";
import { Notify } from "vant";
// Vue.prototype.$Toast = Toast;
// Vue.prototype.$Notify = Notify;
Vue.use(Vant);
//異步加載配置
import axios from "axios";
// axios.defaults.baseURL = 'http://127.0.0.1:3000';
axios.defaults.baseURL = "http://liangwei.tech:3000";
//请求拦截
axios.interceptors.request.use(res => {
  const token = localStorage.getItem("token");
  if (token) {
    res.headers.Authorization = localStorage.getItem("token");
  }
  return res;
});
//响应拦截
axios.interceptors.response.use(res => {
  // 判断是否为4开头的请求失败
  const statusCode = res.data.statusCode;
  const verifyRegExp = /^4\d\d$/;
  const isFail = verifyRegExp.test(statusCode);
  if (isFail) {
    Toast.fail(res.data.message);
    localStorage.removeItem("token");
    localStorage.removeItem("user_id");
    router.push({ path: "/login" }).catch(err => {});
  }
  return res;
});
// 绑定到原型
Vue.prototype.$axios = axios;
Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount("#app");
